package nodes;

import compiler.Compiler;
import compiler.SymbolTable;

import descriptors.AbstractDescr;

public class IfNode extends StatementNode {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private ExpressionNode cond;
	private ListNode<StatementNode> thenPart;
	private AbstractNode elsePart;
	
	public IfNode(ExpressionNode cond, ListNode<StatementNode> thenPart,AbstractNode elsePart,int line, int column){
		super(line,column);
		this.cond=cond;
		this.thenPart=thenPart;
		this.elsePart=elsePart;
	}
	
	@Override
	public AbstractDescr compile(
			SymbolTable symbolTable, Compiler compiler) {
		
		cond.compile(symbolTable, compiler);
		int elseLabel=compiler.newLabel();
		int endLabel=compiler.newLabel();
		compiler.write("BF, "+elseLabel);
		if(thenPart!=null) thenPart.compile(symbolTable, compiler);
		compiler.write("JMP, "+endLabel);
		compiler.write("LABEL, "+elseLabel);
		if(elsePart!=null) elsePart.compile(symbolTable, compiler);
		compiler.write("LABEL, "+endLabel);
		return null;
	}

	@Override
	public void print() {
		trace("IfNode");
		cond.print();
		thenPart.print();
		if(elsePart!=null) {
			elsePart.print();
		}
		unindent();
	}

}
